package com.lagou.homework.dao;

import com.lagou.homework.bean.User;
import com.lagou.homework.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * UserDao接口的实现类
 */
public class UserDaoImp implements UserDao {
    // 重写登录方法
    @Override
    public User userLogin(User user) {

        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            // 1.准备数据库连接
            connection = DbUtil.getConnection();
            // 2.准备sql语句以及预处理语句
            String sql = "select * from t_user where userName = ? and password = ?";
            ps = connection.prepareStatement(sql);
            // 3.设置占位符，执行sql语句并获取结果集对象
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getPassword());
            resultSet = ps.executeQuery();
            // 4.判断结果集对象是否为空，若非空说明登录成功，返回User对象
            if (resultSet.next()) {
                User tu = new User(resultSet.getString("userName"), resultSet.getString("password"));
                return tu; // t代表temporary，临时的
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 5.关闭相关资源
            try {
                DbUtil.close(connection, ps, resultSet);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        return null;
    }
}
